﻿using LPLS.Commons.DBModule;
using LPLS.DBEntities;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace LPLS.DBServices
{
    // 数据库配置类
    public static class DatabaseConfig
    {
        public static Dictionary<string, SqlSugarScope> ConfiguredDbContexts { get; private set; }

        public static void InitDataBaseConfig()
        {
            ConfiguredDbContexts = new Dictionary<string, SqlSugarScope>();

            // 加载配置文件
            var configuration = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .Build();

            // 获取Databases配置节的子节点
            var databasesSection = configuration.GetSection("Databases");

            foreach (var dbSection in databasesSection.GetChildren())
            {
                var dbKey = dbSection.Key; // 如 "SqlServer1"
                var connectionString = dbSection["ConnectionString"];
                var dbType = dbSection["DbType"];
                var isCodeFirst = bool.Parse(dbSection["IsCodeFirst"] ?? "false");
                var isEnable = bool.Parse(dbSection["IsEnable"] ?? "true");

               
                // 参数校验
                if (string.IsNullOrEmpty(connectionString) || string.IsNullOrEmpty(dbType))
                {
                    continue;
                }

                // 创建数据库客户端
                var dbContext = new SqlSugarScope(new ConnectionConfig()
                {
                    ConnectionString = connectionString,
                    DbType = (DbType)Enum.Parse(typeof(DbType), dbType, true),
                    IsAutoCloseConnection = true
                });

                // 处理CodeFirst
                if (isCodeFirst)
                {
                    dbContext.DbMaintenance.CreateDatabase();
                    var entityTypes = GetEntityTypesForDbKey(dbKey);
                    dbContext.CodeFirst.InitTables(entityTypes.ToArray());
                }

                ConfiguredDbContexts.Add(dbKey, dbContext);
            }
        }

        static DatabaseConfig()
        {
        }

        private static List<Type> GetEntityTypesForDbKey(string dbKey)
        {
        
            var entityTypes = new List<Type>();
            var entityAssembly = Assembly.Load("LPLS.DBEntities");
            var entityClasses = entityAssembly.GetTypes()
                .Where(t => t.IsClass );

            foreach (var entityClass in entityClasses)
            {
                var dbKeyAttribute = entityClass.GetCustomAttribute<DatabaseKeyAttribute>();
                if (dbKeyAttribute != null && dbKeyAttribute.DbKey.ToString().ToUpper() == dbKey.ToUpper())
                {
                    entityTypes.Add(entityClass);
                }
            }

            return entityTypes;
        }
    }
}